/**
 * 
 */
package info.niwota.start;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class ScreenService extends Service {
	private static final String TAG = "ScreenService";

	public class LocalBinder extends Binder {
		ScreenService getService() {
			return ScreenService.this;
		}
	}

	private final IBinder binder = new LocalBinder();

	@Override
	public IBinder onBind(Intent i) {
		return binder;
	}

	private IntentFilter intentFilter;

	private boolean paused = false;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		
		private String state = null;
		
		private long offtime = 0;
		
		private long pausetime = 0;

		private final long MIN_ELAPSE = 900;
		
		private final long MIN_PAUSE = 3000;

		public void onReceive(Context ctx, Intent intent) {
			final String action = intent.getAction();
			
			if (Debug.DEBUG) {
				Log.d(TAG, "action: " + action + " phone state: " + state +" paused: " + paused);
			}
			
			if (Intents.ACTION_POWERUP_QUIT.equals(action)) {
				paused = false;
				pausetime = 0;
				PowerupActivity.ensureIfRunning(ctx, true);
				return;
			}
			//
			if (Intents.ACTION_POWERUP_SUSPEND.equals(action)
					|| Intents.ALARM_ALERT.equals(action) 
					|| Intents.ALARM_ALERT1.equals(action)
					|| Intents.ALARM_ALERT2.equals(action)
					|| Intents.ALARM_ALERT_SAMSUNG.equals(action)) {
				paused  = true;
				pausetime = System.currentTimeMillis();
				return;
			}
			
			//
			if (Intents.ACTION_PHONE_STATE.equals(action)) {
				state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
				
				if (Debug.DEBUG) {
					Log.d(TAG, "phone state change, state: " + state + " extras: " + intent.getExtras());
				}
				
				if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
					//set by PowerupActivity
					final boolean active = ApplicationContext.isActive();
					if (Debug.DEBUG) {
						Log.d(TAG,
								"phone state change,  state: "
										+ state + " active: " + active);
					}
					
					//
					if (active) {
						PowerupActivity.ensureIfRunning(ctx);
					}
					//reset
					state = null;
					ApplicationContext.setActive(false);
				}
				
				return;
			}
			
			if (Intent.ACTION_SCREEN_OFF.equals(action)) {
				offtime = System.currentTimeMillis();
				return;
			}
			
			//screen on
			
			if (paused) {
				final long elapse = System.currentTimeMillis() - pausetime;
				
				if (Debug.DEBUG) {
					Log.d(TAG, "Paused now, elapse: "+ elapse + " action: " + action);
				}
				
				if (elapse < MIN_PAUSE) {
					if (Debug.DEBUG) {
						Log.d(TAG, "too soon: "+ elapse + " ignore action: " + action);
					}
					return;
				}
			}
			pausetime = 0;
			
			if (Intent.ACTION_SCREEN_ON.equals(action)) {
				//ignore if incoming call
				if (state != null) {
					if (Debug.DEBUG) {
						Log.d(TAG, "on a call now, ignore action: " + action + " phone state: " + state);
					}
					return;
				}
				
				//ignore on immediately following off
				final long elapse = System.currentTimeMillis() - offtime;
				
				if (Debug.DEBUG) {
					Log.d(TAG, "Elapsed: "+ elapse + " action: " + action + " phone state: " + state);
				}
				
				if (elapse < MIN_ELAPSE) {
					if (Debug.DEBUG) {
						Log.d(TAG, "too soon: "+ elapse + " ignore action: " + action + " phone state: " + state);
					}
					return;
				}
				
				PowerupActivity.ensureIfRunning(ctx);
			}
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();

		if (Debug.DEBUG) {
			Log.d(TAG, "onCreate");
		}

		//
		try {
			if (Debug.DEBUG) {
				Log.d(TAG, "receiver: " + receiver);
			}

			intentFilter = new IntentFilter();
			
			intentFilter.addAction(Intent.ACTION_SCREEN_ON);
			intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
			
			//phone
			intentFilter.addAction(Intents.ACTION_PHONE_STATE);
			
			//alarm
			intentFilter.addAction(Intents.ALARM_ALERT);
			intentFilter.addAction(Intents.ALARM_ALERT1);
			intentFilter.addAction(Intents.ALARM_ALERT2);
			intentFilter.addAction(Intents.ALARM_ALERT_SAMSUNG);
			
			//custom
			intentFilter.addAction(Intents.ACTION_POWERUP_QUIT);
			intentFilter.addAction(Intents.ACTION_POWERUP_SUSPEND);
			//
			registerReceiver(receiver, intentFilter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onDestroy() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onDestroy");
		}

		try {
			if (receiver != null) {
				unregisterReceiver(receiver);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		receiver = null;

		//
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		handleCommand(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand(intent);
		return START_STICKY;
	}

	private void handleCommand(Intent intent) {
		if (Debug.DEBUG) {
			Log.d(TAG, "handleCommand intent: " + intent);
		}
		//
	}

	public static void shutdown(Context ctx) {
		Intent intent = new Intent(ctx, ScreenService.class);
		try {
			ctx.stopService(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void startup(Context ctx) {
		Intent intent = new Intent(ctx, ScreenService.class);
		try {
			ctx.startService(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
